﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.BS.Job.RequestClient;
using UFSoft.UBF.UI.ControlModel;
using UFSoft.UBF.UI.Engine.Builder;
using UFSoft.UBF.UI.IView;
using UFSoft.UBF.UI.MD.Runtime;
using UFSoft.UBF.UI.WebControlAdapter;
using UFSoft.UBF.Util.Log;
using UFIDA.U9.MFG.Complete.CompleteApplyRpt.RcvRptUI;
using UFIDA.U9.UI.PDHelper;
using UFIDA.U9.Lot;

namespace UFIDA.U9.Cust.XH.PlugUI
{
    /// <summary>
    /// 成品入库界面UI插件
    /// </summary>
    public class BCompleteRcvRptUIWebPart : UFSoft.UBF.UI.Custom.ExtendedPartBase
    {

        #region 字段与属性                                       

        private UFIDA.U9.MFG.Complete.CompleteApplyRpt.RcvRptUI.RcvRptMainUIFormWebPart part;
        private static ILogger logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        IUFButton btnBack = null;
        #endregion
        public override void AfterInit(UFSoft.UBF.UI.IView.IPart Part, EventArgs args)
        {
            //首先调用原来的事件
            base.AfterInit(Part, args);
            part = Part as UFIDA.U9.MFG.Complete.CompleteApplyRpt.RcvRptUI.RcvRptMainUIFormWebPart;

            if (part == null)
                return;
            IUFCard card = (IUFCard)part.GetUFControlByName(part.TopLevelContainer, "Card0");//一般情况下名称为Card0,具体请使用F12查看
            if (card != null && btnBack == null)
            {

                IUFButton btGetLingliaoDialog = new UFWebButtonAdapter();
                btGetLingliaoDialog.Text = "参照领料单";
                btGetLingliaoDialog.ID = "btGetLingliaoDialog";
                btGetLingliaoDialog.AutoPostBack = true;
                card.Controls.Add(btGetLingliaoDialog);
                btGetLingliaoDialog.Click += new EventHandler(btGetLingliaoDialog_Click);
                CommonFunction.Layout(card, btGetLingliaoDialog, 10, 0);   //一般为从左往右按钮个数乘以2

                btnBack = new UFWebButtonAdapter();
                btnBack.Text = "领料参数回调";
                btnBack.ID = "btnBack";
                btnBack.Visible = false;
                card.Controls.Add(btnBack);
                btnBack.Click += new EventHandler(btnBack_Click);
                CommonFunction.Layout(card, btnBack, 12, 0);   //一般为从左往右按钮个数乘以2
            }
        }
        private void btGetLingliaoDialog_Click(object sender, EventArgs e)
        {
            this.part.DataCollect();
            this.part.DataBind();

            if (this.part.Model.RcvRptDocLine.FocusedRecord != null)
            {
                string modoc = this.part.Model.RcvRptDocLine.FocusedRecord.MO_DocNo;
                //modoc = "MO-0003";
                if (!string.IsNullOrEmpty(modoc))
                {
                    this.part.CurrentState["LotData"] = null;//现将选中领料单参数数据清空
                    //参照拉单                               
                    this.part.CurrentState["MODoc"] = modoc;
                    //this.part.ShowAtlasModalDialog("746e0f3b-22e7-464e-a1a9-b91115b961f0", "领料单参照", "696", "504", this.part.TaskId.ToString(), null, true, false, false, PartShowType.ModalRef);
                    this.part.ShowAtlasModalDialog(this.btnBack, "746e0f3b-22e7-464e-a1a9-b91115b961f0", "领料单参照", "600", "420", this.part.TaskId.ToString(), null, true, true, true, PartShowType.ModalRef);
                }
                else
                {
                    this.part.ShowWindowStatus("请在入库单选中生产订单行后进行拉单", true);
                }

            }
            else
            {
                this.part.ShowWindowStatus("请在入库单选中生产订单行后进行拉单", true);
            }

        }

        private void LoadDataToPage()
        {
            try
            {
                if (this.part.CurrentState["LotData"] != null)
                {
                    DataTable dt = this.part.CurrentState["LotData"] as DataTable;
                    RcvRptDocLineRecord line = this.part.Model.RcvRptDocLine.FocusedRecord;
                    string itemcode = line.Item_Code;
                    int i = 0;
                    foreach (DataRow item in dt.Rows)
                    {
                        string lotcode = item["LotNo"].ToString();
                        DateTime effdate = Convert.ToDateTime(string.IsNullOrEmpty(item["LotEffectivedate"]?.ToString()) ? DateTime.Now : item["LotEffectivedate"]);
                        DateTime disdate = Convert.ToDateTime(string.IsNullOrEmpty(item["LotDisableDate"]?.ToString()) ? DateTime.Now.AddYears(1) : item["LotDisableDate"]);
                        long itemid = line.Item;                        
                        string res = AddLotBP(lotcode, "100", itemid.ToString(), effdate, disdate);
                        if (i == 0)
                        {
                            decimal scqty = (decimal)this.part.Model.RcvRptDocLine.FocusedRecord.RcvQtyByProductUOM;
                            decimal kcqty = (decimal)this.part.Model.RcvRptDocLine.FocusedRecord.RcvQtyByWhUOM / scqty;
                            decimal cbqty = (decimal)this.part.Model.RcvRptDocLine.FocusedRecord.RcvQtyByCostUom / scqty;
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvQtyByProductUOM = scqty / scqty;
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvQtyByCostUom = cbqty;
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvQtyByWhUOM = kcqty;
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvLotNo = lotcode;                           
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvLotMaster = Convert.ToInt64(res);
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvLotMaster_Code = lotcode;
                        }
                        else
                        {

                            RcvRptDocLineRecord copyrd = (RcvRptDocLineRecord)this.part.Model.RcvRptDocLine.FocusedRecord.CopyClone();
                            RcvRptDocLineRecord rd = this.part.Model.RcvRptDocLine.AddNewUIRecord();
                            copyrd.CopyTo(rd);
                            rd.LineNum = (this.part.Model.RcvRptDocLine.RecordCount) * 10;
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvLotNo = lotcode;
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvLotMaster = Convert.ToInt64(res);
                            this.part.Model.RcvRptDocLine.FocusedRecord.RcvLotMaster_Code = lotcode;
                        }
                        i++;
                    }
                    this.part.DataCollect();
                    this.part.DataBind();

                }
            }
            catch (Exception e)
            {
                if (e.Message.Contains("零"))
                {
                    this.part.Model.ErrorMessage.Message = "拉取批号异常：数量不能为0;";
                }
                else
                {
                    this.part.Model.ErrorMessage.Message = "异常信息："+e.Message;
                }
                
                //throw e;
            }
        }

        public string AddLotBP(string LotCode, string lotrule, string item, DateTime effdate, DateTime disdate)
        {
            //客开BP
            UFIDA.U9.Cust.XIHE.AddLotMasterBP.AddLotBP.Proxy.AddBPProxy addBP = new XIHE.AddLotMasterBP.AddLotBP.Proxy.AddBPProxy();
            addBP.LotCode = LotCode;
            addBP.LotRule = lotrule;
            addBP.Item = item;
            addBP.EffDate = effdate;
            addBP.DisDate = disdate;
            string res = addBP.Do();
            return res;

            ////新增批号  系统BP
            //UFIDA.U9.Lot.Proxy.BatchCreateLotSVProxy batchCreateLotSV = new UFIDA.U9.Lot.Proxy.BatchCreateLotSVProxy();
            ////批号规则
            //UFIDA.U9.CBO.SCM.Lot.LotCodingRule lotCodingRule = Item.InventoryInfo.LotParam.LotCodingParameter.LotCodingRules[0];
            //UFIDA.U9.Lot.LotCreateDTOData lotDTO = new LotCreateDTOData()
            //{
            //    LotCodingRule = lotCodingRule.ID
            //};
            //UFIDA.U9.CBO.DTOs.KeyFlexFieldDTOData keyFlexFieldDTOData = new UFIDA.U9.CBO.DTOs.KeyFlexFieldDTOData();
            //keyFlexFieldDTOData.Code = LotCode;
            //lotDTO.KeyFlexFieldDTO = keyFlexFieldDTOData;

            //lotDTO.UseOrg =Convert.ToInt64(PDContext.Current.OrgID);
            //lotDTO.ItemMaster = Item.ID;
            //lotDTO.Lot = LotCode;
            //batchCreateLotSV.CreateMode = 1;
            //batchCreateLotSV.LotCreateDTO = lotDTO;
            //batchCreateLotSV.Quantity = 1;
            //List<Lot.LotMasterData> lotMasterDataList = batchCreateLotSV.Do();
            //return lotMasterDataList[0].id;

        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            LoadDataToPage();
        }



    }
}
